import { ReactElement, useRef, useEffect, RefObject } from 'react'
import { Form, Input, Row, Col, Space, Button, FormInstance } from 'antd'
import { History, Location } from 'history'
import style from './index.module.less'
import { ConditionSchema } from '@src/components/schema/condition'
import { useLocation } from 'react-router-dom'
import { setSearch, getSearch } from '@src/assets/js/tool'

const { Item } = Form

export function formatCondition (d: { [k: string]: any }): ConditionSchema[] {
  const r: ConditionSchema[] = []
  if (typeof d.title === 'string') {
    r.push({ k: 'title', o: 'like', v: `%${d.title}%` })
  }
  return r
}

// 改变搜索条件
function changeSearch (d: { [k: string]: any }, params: {[k: string]: any},setParams: (v: {[k: string]: any}) => void): void {
  const keys = ['title']
  keys.forEach(key => {
    if (d[key] === undefined) {
      d[key] = undefined
    }
  })
  d.page = 1
  setParams({ ...params, ...d })
}

function initForm (l: Location, formRef: RefObject<FormInstance>): void {
  const c = formRef.current
  if (c === null || l === null) {
    return undefined
  }
  const o = getSearch()
  const r: { [k: string]: any } = {}
  if (typeof o.title === 'string') {
    r.title = o.title
  }
  c.setFieldsValue(r)
}

interface Props {
  params: {[k: string]: any},
  setParams: (v: {[k: string]: any}) => void
}

function Main ({ params, setParams }: Props): ReactElement {
  const l = useLocation()
  const ref = useRef<FormInstance>(null)
  useEffect(() => {
    if (l !== null) {
      initForm(l, ref)
    }
  }, [])
  return (
    <div className={style.container}>
      <Form ref={ref} labelCol={{ flex: '80px' }} initialValues={{}} onFinish={d => changeSearch(d, params, setParams)} onReset={() => ref.current?.submit()}>
        <Row gutter={48}>
          <Col span={8}>
            <Item label='查询' name='title'>
              <Input placeholder='请输入名称' allowClear />
            </Item>
          </Col>
          <Col span={8} />
          <Col span={8} className={style.btns}>
            <Space>
              <Button type='primary' htmlType='submit'>查询</Button>
              <Button htmlType='reset'>重置</Button>
            </Space>
          </Col>
        </Row>
      </Form>
    </div>
  )
}

export default Main
